package com.xxxx.server.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.xxxx.server.mapper.EmployeeMapper;
import com.xxxx.server.page.EmployeeExcel;
import com.xxxx.server.page.RespPageBean;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.*;
import com.xxxx.server.utils.ExcelImportData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/employee/basic")
@Slf4j
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private INationService nationService;

    @Autowired
    private IJoblevelService joblevelService;

    @Autowired
    private IPoliticsStatusService politicsStatusService;

    @Autowired
    private IDepartmentService departmentService;


    //进入员工页面 展示员工数据信息
    @GetMapping("/")
    @ApiOperation(value = "查询所有员工对象（分页）")
    public RespPageBean getEmployeeByPage(
            @RequestParam(defaultValue = "1") Integer currentPage
            , @RequestParam(defaultValue = "10") Integer size
            , Employee employee
            , LocalDate[] beginDateScope) {
        return employeeService.getEmployeeByPage(currentPage, size, employee,beginDateScope);
    }

    @GetMapping("/positions")
    @ApiOperation(value = "查询出所有的职位")
    public List<Position> positions(){
        return positionService.list();
    }
    @GetMapping("/nations")
    @ApiOperation(value = "查询出所有的名族")
    public List<Nation> nations(){
        return nationService.list();
    }
    @GetMapping("/joblevels")
    @ApiOperation(value = "查询出所有的职称")
    public List<Joblevel> joblevels(){
        return joblevelService.list();
    }
    @GetMapping("/politicsstatus")
    @ApiOperation(value = "查询出所有的政治面貌")
    public List<PoliticsStatus> politicsStatuses(){
        return politicsStatusService.list();
    }
    @GetMapping("/deps")
    @ApiOperation(value = "查询出所有的所属部门")
    public  List<Department>  departments(){
        return departmentService.getAllDepartment();
    }
    @GetMapping("/maxWorkID")
    @ApiOperation(value = "查询出工号")
    public RespBean maxWorkID() {
        RespBean respBean = employeeService.maxWorkID();
        return respBean;
    }

    @ApiOperation("添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){
        return employeeService.addEmp(employee);
    }

    @ApiOperation("更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean delEmp(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response) {
        List<Employee> employeeList = employeeService.getEmployee(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employeeList);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();//获取输出流
            workbook.write(outputStream);        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    @Transactional
    public RespBean importEmployee(MultipartFile multipartFile) {
        ImportParams importParams = new ImportParams();
        //设置第一行为标题行，避免系统将标题行作为数据导入
        importParams.setTitleRows(1);
        //查询民族对象
        List<Nation> nationList = nationService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Employee.class, importParams);
            //设置关联属性的id值
            employeeList.forEach(employee -> {

                /**
                 *
                 *         employeeList.forEach(employee -> {
                 *             //获取每条employee对象中的nation名字在nationList中的索引
                 *             int nationIndex = nationList.indexOf(new Nation(employee.getNation().getName()));
                 *             //获取这个nation名字在nationList中对应索引的id就是我们想设置的id
                 *             Integer nationId = nationList.get(nationIndex).getId();
                 *             employee.setNationId(nationId);
                 *         });
                 *
                 *
                 *         employeeList.forEach(employee -> {
                 *             //获取每条employee对象中的nation名字在nationList中的索引，用Nation里定义的有参方法取出id
                 *             //indexOf(String s)返回指定字符在字符串中第一次出现处的索引
                 *             int nationIndex = nationList.indexOf(new Nation(employee.getNation().getName()));
                 *             //通过索引可以获取nation这个对象，然后getId就可以获取id，获取这个nation名字在nationList中对应索引的id就是我们想设置的id
                 *             Integer nationId = nationList.get(nationIndex).getId();
                 *             employee.setNationId(nationId);
                 *         });
                 */
                //设置nationId
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
            });
            if (employeeService.saveBatch(employeeList)){
                return RespBean.success("员工导入成功！");
            }
            return RespBean.error("员工导入失败！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("员工导入失败！");
    }

    /*@ApiOperation(value = "导入员工数据")
    @PostMapping(value = "/import")
    public RespBean importEmployee(MultipartFile file){
        ImportParams importParams = new ImportParams();
        //去掉标题行
        importParams.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            list.forEach(employee->{
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
            });
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }*/
/*
    //添加员工信息
    @PostMapping("/")
    @ApiOperation(value = "添加员工信息")
    public RespBean addEmployee(@RequestBody EmployeeAdd employeeAdd){
        //service 层做校验
        if(employeeService.saveEmployee(employeeAdd) == 1){
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！！！");
    }



    //更新员工信息
   @PutMapping("/")
   @ApiOperation(value = "更新员工信息")
    public RespBean updateEmployee(@RequestBody Employee employee){
        if(employeeService.updateEmployeeById(employee) == 1){
            return RespBean.success("更新成功！！！");
        }
        return RespBean.error("更新失败！！");
    }



    //删除员工信息
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除员工信息")
    public RespBean deleteEmployee(@PathVariable Integer id){
        if(employeeService.removeEmployeeById(id) == 1){
            return RespBean.success("删除成功！！！");
        }
        return RespBean.error("删除失败！！");
    }



    @GetMapping("/export")
    @ApiOperation(value = "导出数据")
    public void exportData(HttpServletResponse response)  {
        List< Employee > exports = employeeService.findAllEmployee();
        //List< Employee > exports = (List<Employee>) employeeService.getEmployeeByPage(null,null,new Employee(),null).getData();
        try {
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            String fileName = new String("Student信息表".getBytes("utf-8"),"utf-8");
            Sheet sheet = new Sheet(1,0,Employee.class);
            sheet.setSheetName("sheet1");
            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            writer.write(exports,sheet);
            writer.finish();
            out.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }



    //导入excel
    @PostMapping("/import")
    @ApiOperation(value = "导入数据")
    public Object excelImportData(MultipartFile excel, @RequestParam(defaultValue = "1") int headLineNum) throws IOException {
        List<Object> empExcel = null;
        try {
            empExcel = employeeService.importEmployeeExcel(excel, new Employee(), headLineNum);
            if (empExcel == null) {
                log.error("插入数据库失败!");
                return "插入数据库失败!";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("无法导入数据库,请查看配置参数是否正确!");
            return "无法导入数据库,请查看配置参数是否正确!";
        }
        log.info("恭喜,导入excel成功!");
        return empExcel;
    }
*/


}
